package com.jiantong.admin.controller.dongjiantong;

import com.jiantong.admin.controller.DjtBaseController;
import com.jiantong.admin.dto.CityAreaDto;
import com.jiantong.admin.dto.Fac_SuperDto;
import com.jiantong.admin.model.Common;
import com.jiantong.admin.model.PagingMz;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.model.GovernmentUserDuty;
import com.jiantong.user.model.User;
import com.jiantong.user.model.UserProfile;
import com.jiantong.user.service.*;
import com.jiantong.work.model.SupervisionRecords;
import com.jiantong.work.service.SupervisionRecordsReadService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by cao on 2017/7/17.
 * 督察管理
 */
@Controller
@RequestMapping("/djt/inspector")
public class InspectorsController extends DjtBaseController {

    private static final String BaseViews = VIEWS + "inspectors/";

    @GetMapping("inspguide")
    private String InspectorGuide(Model model, HttpServletRequest request, HttpServletResponse response) {
        Map mapuser = getarea(response, request);


        model.addAttribute("username", mapuser.get("username"));
        Common common = new Common(breedFactoryReadService, butcherFactoryReadService);
        List areaList = common.serachCityAreaDtoInBreefctory();
        List<BreedFactory> facList = breedFactoryReadService.findByArea(new HashMap<>()).getResult();
        List<String> nameList = supervisionRecordsReadService.findAllName().getResult();
        model.addAttribute("nameList", nameList);
        model.addAttribute("facList", facList);
        model.addAttribute("areaList", areaList);
        model.addAttribute("username", mapuser.get("username"));
        return BaseViews + "inspguide";
    }

    @RpcConsumer
    private GovernmentUserDutyReadService governmentUserDutyReadService;

    @GetMapping("insprecord")
    private String InspectorRecord() {
        return BaseViews + "insprecord";
    }

    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;
    @RpcConsumer
    private ButcherFactoryReadService butcherFactoryReadService;
    @RpcConsumer
    private SupervisionRecordsReadService supervisionRecordsReadService;
    @RpcConsumer
    private UserReadService userReadService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;

    //首页
    @GetMapping("bddt")
    @ResponseBody
    private Map<String, List<Fac_SuperDto>> bddt(@RequestParam(required = false) Date start,
                                                 @RequestParam(required = false) Date end,
                                                 @RequestParam(required = false) String area,
                                                 @RequestParam(required = false) Integer type,
                                                 @RequestParam(required = false) Integer status,
                                                 @RequestParam(required = false) String name,
                                                 @RequestParam(required = false) String breedfac
    ) {
        Map criteria = new HashMap();
        if (area != null && area.length() > 0) {
            criteria.put("region", area);
        }
        List<BreedFactory> facList = (List<BreedFactory>) breedFactoryReadService.findByArea(criteria).getResult();
        criteria.clear();
        if (start != null) {
            criteria.put("start", start);
        }
        if (end != null) {
            criteria.put("end", end);
        }
        if (type != null && type != 0) {
            criteria.put("breedType", type);
        }
        if (status != null && status != -5) {
            criteria.put("status", status);
        }
        if (name != null && name.length() > 0) {
            criteria.put("userName", name);
        }
        if (breedfac != null && breedfac.length() > 0) {
            criteria.put("breedFactoryName", breedfac);
        }
        Map<String, List<Fac_SuperDto>> reportMap = new HashMap();
        List<SupervisionRecords> datas = supervisionRecordsReadService.pagingcommon(0, 10000, criteria).getResult().getData();
        for (BreedFactory factory : facList) {
            if (datas != null && datas.size() > 0) {
                for (SupervisionRecords records : datas) {
                    if (factory.getId().equals(records.getBreedFactoryId())) {
                        if (reportMap.containsKey(records.getUserName())) {
                            List<Fac_SuperDto> list = reportMap.get(records.getUserName());
                            list.add(new Fac_SuperDto(factory, records));
                            reportMap.put(records.getUserName(), list);
                        } else {
                            List<Fac_SuperDto> list = new ArrayList<>();
                            list.add(new Fac_SuperDto(factory, records));
                            reportMap.put(records.getUserName(), list);
                        }
                    }
                }
            }
        }/* new BMap.Point(116.404, 39.915),
            new BMap.Point(116.405, 39.920),
            new BMap.Point(116.425, 39.900)*/

        /*112.20, 32.08*/

        return reportMap;

    }

    @GetMapping("records")
    private String supervision(Model model, HttpServletRequest request, HttpServletResponse response) {
        Map mapuser = getarea(response, request);
        model.addAttribute("username", mapuser.get("username"));
      // Common common = new Common(breedFactoryReadService, butcherFactoryReadService);
        //List areaList = common.serachCityAreaDtoInBreefctory();
        List<BreedFactory> facList = breedFactoryReadService.findByArea(new HashMap<>()).getResult();
        List<String> nameList = supervisionRecordsReadService.findAllName().getResult();
        model.addAttribute("nameList", nameList);
       // model.addAttribute("facList", facList);
        model.addAttribute("facList",mapuser.get("breedFactorys"));
        model.addAttribute("areaList", mapuser.get("cityAreaDtoList"));
      //  model.addAttribute("areaList", areaList);
        return BaseViews + "supervision-records";
    }

    @GetMapping("recordsindex")
    @ResponseBody
    private PagingMz<Fac_SuperDto> showRecordsIndex(@RequestParam(required = false) Integer page,
                                                    @RequestParam(required = false) Integer rows,
                                                    @RequestParam(required = false) Date start,
                                                    @RequestParam(required = false) Date end,
                                                    @RequestParam(required = false) String area,
                                                    @RequestParam(required = false) Integer type,
                                                    @RequestParam(required = false) Integer status,
                                                    @RequestParam(required = false) String name,
                                                    @RequestParam(required = false) Integer breedfac

    ) {
        Map criteria = new HashMap();

        List<BreedFactory> facList = findFactoryIdByArea(area, -1);
        criteria.clear();
        if (start != null) {
            criteria.put("start", start);
        }
        if (end != null) {
            criteria.put("end", end);
        }
        if (type != null && type != 0) {
            criteria.put("breedType", type);
        }
        if (status != null && status != -5) {
            criteria.put("status", status);
        }
        if (name != null && name.length() > 0) {
            criteria.put("userName", name);
        }
        if (breedfac != null) {
            if (breedfac!=-1) {
                criteria.put("breedFactoryName", breedfac);
            }

        }
        List<Fac_SuperDto> reportList = new ArrayList<>();
        Integer records = 0;
        Paging<SupervisionRecords> all = supervisionRecordsReadService.pagingcommon(0, 10000, criteria).getResult();
        for (BreedFactory factory : facList) {
            if (all != null && !all.isEmpty()) {
                for (SupervisionRecords record : all.getData()) {
                    if (factory.getId().equals(record.getBreedFactoryId())) {
                        records += 1;
                    }
                }
            }

        }
        Paging<SupervisionRecords> paging = supervisionRecordsReadService.pagingcommon(0, rows, criteria).getResult();
        if (paging != null && !paging.isEmpty()) {
            for (BreedFactory factory : facList) {
                for (SupervisionRecords record : paging.getData()) {
                    if (factory.getId().equals(record.getBreedFactoryId())) {
                        reportList.add(new Fac_SuperDto(factory, record));
                    }
                }
            }
        }
        Integer pagetotal = 1;
        records = reportList.size();
        if ("0".equals(records)) {
            BreedFactory breedFactory = new BreedFactory();
            SupervisionRecords records1 = new SupervisionRecords();
            reportList.add(new Fac_SuperDto(breedFactory, records1));
        } else {
            pagetotal = (records - 1) / rows + 1;
        }

        return new PagingMz<>(Long.parseLong(pagetotal.toString()), Long.parseLong(records.toString()), page, reportList);

    }

    @GetMapping("supervisionDetail")
    private String supervisionDetail() {
        return BaseViews + "supervisionDetail";
    }

    @GetMapping("breedByRegion")
    @ResponseBody
    private List<String> breedByRegion(String region) {
        Map map = new HashMap();
        map.put("region", region);
        List<String> nameList = new ArrayList<>();
        List<BreedFactory> breedFactorys = (List<BreedFactory>) breedFactoryReadService.findByArea(map).getResult();
        if (breedFactorys != null && breedFactorys.size() > 0) {
            for (BreedFactory breedFactory : breedFactorys) {
                nameList.add(breedFactory.getName());
            }

        }
        return nameList;
    }


    public Map getarea(HttpServletResponse response, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        list.add("province");
        list.add("city");
        list.add("region");
        list.add("street");
        list.add("village");
        Cookie[] cookies = null;
        cookies = request.getCookies();
        String name = "";
        Map map = new HashMap();
        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("djtid")) {
                String id = cookie.getValue();
                int Id = Integer.parseInt(id);
                Response<User> userResponse = userReadService.findById(Integer.toUnsignedLong(Id));
                name = userResponse.getResult().getName();
                map.put("username", name);
                switch (userResponse.getResult().getAreaLevel()) {
                    case 1:
                        UserProfile userProfile = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String Province = userProfile.getProvince();
                        Map map6 = new HashMap();
                        map6.put("province", Province);
                        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map6).getResult();
                        //获取所有省下城市

                        Map map1 = new HashMap();
                        map1.put("area1", list.get(1));
                        map1.put("area2", list.get(0));
                        map1.put("area3", Province);
                        List<String> citys = breedFactoryReadService.serachAllregion1(map1);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList = new ArrayList<>();
                        for (String city : citys) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(2));
                            map2.put("area2", list.get(1));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList);
                        map.put("breedFactorys", breedFactoryList);
                        //switch break;
                        break;
                    case 2:
                        UserProfile userProfile2 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String city1 = userProfile2.getCity();
                        Map map7 = new HashMap();
                        map7.put("city", city1);
                        List<BreedFactory> breedFactoryList1 = (List<BreedFactory>) breedFactoryReadService.findByArea(map7).getResult();
                        //获取所有省下城市

                        Map map21 = new HashMap();
                        map21.put("area1", list.get(2));
                        map21.put("area2", list.get(1));
                        map21.put("area3", city1);
                        List<String> citys2 = breedFactoryReadService.serachAllregion1(map21);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList1 = new ArrayList<>();
                        for (String city : citys2) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(3));
                            map2.put("area2", list.get(2));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList1.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList1);
                        map.put("breedFactorys", breedFactoryList1);
                        //switch break;
                        break;
                    case 3://区
                        UserProfile userProfile3 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String region = userProfile3.getRegion();
                        Map map36 = new HashMap();
                        map36.put("region", region);
                        List<BreedFactory> breedFactoryList3 = (List<BreedFactory>) breedFactoryReadService.findByArea(map36).getResult();
                        //获取所有区下城市镇

                        Map map31 = new HashMap();
                        map31.put("area1", list.get(3));
                        map31.put("area2", list.get(2));
                        map31.put("area3", region);
                        List<String> citys3 = breedFactoryReadService.serachAllregion1(map31);
                        //获取对应镇 对应村
                        List<CityAreaDto> cityAreaDtoList3 = new ArrayList<>();
                        for (String city : citys3) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(4));
                            map2.put("area2", list.get(3));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList3.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList3);
                        map.put("breedFactorys", breedFactoryList3);
                        //switch break;
                        break;
                    case 4://镇
                        UserProfile userProfile4 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String street = userProfile4.getStreet();
                        Map map46 = new HashMap();
                        map46.put("street", street);
                        List<BreedFactory> breedFactoryList4 = (List<BreedFactory>) breedFactoryReadService.findByArea(map46).getResult();
                        //获取所有镇下所有村

                        Map map41 = new HashMap();
                        map41.put("area1", list.get(4));
                        map41.put("area2", list.get(3));
                        map41.put("area3", street);
                        List<String> citys4 = breedFactoryReadService.serachAllregion1(map41);//所有村

                        List<CityAreaDto> cityAreaDtoList4 = new ArrayList<>();

                        CityAreaDto cityAreaDto = new CityAreaDto();

                        cityAreaDto.setCity(street);
                        cityAreaDto.setRegions(citys4);
                        cityAreaDtoList4.add(cityAreaDto);


                        map.put("cityAreaDtoList", cityAreaDtoList4);
                        map.put("breedFactorys", breedFactoryList4);
                        //switch break;
                        break;
                    case 5://村
                        List<GovernmentUserDuty> governmentUserDutyList = governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userResponse.getResult().getId(), null).getResult();
                        List<Long> longlist = new ArrayList<>();
                        if (governmentUserDutyList.size()!=0){
                            for (GovernmentUserDuty governmentUserDuty : governmentUserDutyList) {
                                longlist.add(governmentUserDuty.getFactoryOrPointId());
                            }
                        }
                        List<String> villages = new ArrayList<>();
                        List<BreedFactory> breedFactoryList2 = breedFactoryReadService.findBreedFactoryDtoByIds(longlist).getResult();
                        for (BreedFactory breedFactory : breedFactoryList2) {
                            villages.add(breedFactory.getVillage());
                            ;
                        }

                        List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(villages));


                        List<CityAreaDto> cityAreaDtoList5 = new ArrayList<>();

                        CityAreaDto cityAreaDto1 = new CityAreaDto();
                        cityAreaDto1.setCity(" ");

                        // cityAreaDto1.setCity(village);
                        cityAreaDto1.setRegions(listWithoutDup);

                        cityAreaDtoList5.add(cityAreaDto1);


                        map.put("cityAreaDtoList", cityAreaDtoList5);
                        map.put("breedFactorys", breedFactoryList2);
                        //switch break;
                        break;
                }


                break;
            }

        }

        return map;
    }


    public List findFactoryIdByArea(@RequestParam String region, @RequestParam int breedType) {

        Map map = new HashMap();
        if (breedType == -1) {
            map.put("breedType", null);
        } else {
            map.put("breedType", breedType);
        }
        List<String> list1 = new ArrayList<>();
        String[] list = region.split(",");

        for (int i = 0; i < list.length; i++) {
            list1.add(list[i]);
        }
        map.put("areas", list1);

        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map).getResult();

        return breedFactoryList;
    }


}
